<template>
	<view>

		<u-toast ref="uToast"></u-toast><!-- 弹窗 -->
		<!-- :rules表单校验规则，通过rules属性来指定表单项的校验规则 ref:给表单设置一个引用名称 errorType设置表单错误提示方式
		label-position表单项的标签位置为左对齐 label-align设置标签文字对齐方式为左对齐-->
		<view class="form-container">
			<u-form :model="reportForm" :rules="rules" ref="reportForm" :errorType="['toast']" label-position="left"
				label-width="150" label-align="left" class="shzy-form">

				<template>
					<view class="form-list">
						<!-- 生产人员 @change="handleChange"-->
						<u-form-item label="作业人员" prop="operatorId" label-width="200" required class="form-item">
							<shzy-org-select v-model="reportForm.operatorId" :options="employeeNameList"
								@changeFun="employeeChange"></shzy-org-select>
						</u-form-item>
						<!-- 开始时间 -->
						<u-form-item label="实际开始时间" prop="actualStartTime" label-width="200" required class="form-item">
							<shzy-date-time type="datetime" v-model="reportForm.actualStartTime"
								@change="getWorkHours"></shzy-date-time>
						</u-form-item>
						<!-- 结束时间 -->
						<u-form-item label="实际完成时间" prop="actualEndTime" label-width="200" required class="form-item">
							<shzy-date-time type="datetime" v-model="reportForm.actualEndTime"
								@change="getWorkHours"></shzy-date-time>
						</u-form-item>
						<!-- 报工数量-->
						<u-form-item label="报工数量" prop="qty" label-width="200" required class="form-item">
							<u-input v-model="reportForm.qty" placeholder="" :border="border" type="number"></u-input>
						</u-form-item>
						<!-- 不合格数量-->
						<u-form-item label="不合格数量" v-show="type == '不合格'" required prop="ngQty" label-width="200"
							class="form-item">
							<u-input v-model="reportForm.ngQty" placeholder="" :border="border" type="number"></u-input>
						</u-form-item>
						<!-- 工时 -->
						<u-form-item label="工时" prop="workHours" required label-width="200" class="form-item">
							<u-input v-model="reportForm.workHours" placeholder="" :border="border" type ="number"></u-input>
							<text style="margin-left: 20px;">分钟</text>
						</u-form-item>
						<!-- 备注 -->
						<u-form-item label="备注" prop="remark" label-width="200" class="form-item">
							<u-input v-model="reportForm.remark" placeholder="" :border="border" type="textarea"></u-input>
						</u-form-item>
					</view>
				</template>
			</u-form>

		</view>

		<!-- 按钮 -->
		<view class="buttom-actions-addsample">
			<u-button class="buttom-btn" style="" type="primary" @click="confirm">提交报工</u-button>
		</view>

	</view>
</template>

<script>
	import {
		createWorkReport,getUserList
	} from '@/api/q1/business/workorder/workorder.js'

	export default {

		data() {
			const qtyValidator = (rule, value, callback) => {
				if (value.length == 0) {
					callback(new Error("请输入报工数量"));
				} else {

					if (parseInt(this.reportForm.qty) > parseInt(this.dataForm.qty)) {
						callback(new Error("报工数量不能大于工单数量"));
					} else {
						callback();
					}

				}
			};
			const ngQtyValidator = (rule, value, callback) => {
				if (value.length == 0) {
					callback(new Error("请输入不合格数量"));
				} else {
					var _reg = /^\d+$/
					if (!_reg.test(value)) {
						callback(new Error("请输入数字"));
					} else {
						if (parseInt(this.reportForm.ngQty) > parseInt(this.reportForm.qty)) {
							callback(new Error("不合格数量不能大于报工数量"));
						} else {
							callback();
						}
					}
				}
			};
			const actualStartTimeValidator = (rule, value, callback) => {
				if (value.length == 0) {
					callback(new Error("请选择实际开始时间"));
				} else {
					let date1 = new Date(this.reportForm.actualStartTime);
					let date2 = new Date(this.reportForm.actualEndTime);
					if (date1.getTime() > date2.getTime()) {
						callback(new Error("实际开始时间必须小于或等于实际完成时间"));
					} else {
						callback();
					}
				}
			};
			const actualEndTimeValidator = (rule, value, callback) => {
				if (value.length == 0) {
					callback(new Error("请选择实际完成时间"));
				} else {
					let date1 = new Date(this.reportForm.actualStartTime);
					let date2 = new Date(this.reportForm.actualEndTime);
					//console.log(date1.getTime(), date2.getTime())
					if (date1.getTime() > date2.getTime()) {
						callback(new Error("实际完成时间必须大于或等于实际开始时间"));
					} else {
						callback();
					}
				}
			};

			const workHoursValidator = (rule, value, callback) => {
				
				if (value.length == 0) {
					callback(new Error("请输入工时"));
				}else{
					callback();
				}
				
			};
			
			return {
				border: true,
				reportForm: {
					workOrderId: "",
					status: "OK",
					operatorId: "",
					qty: "",
					ngQty: 0,
					actualStartTime: "",
					actualEndTime: "",
					workHours: "",
					remark: "",
				},
				dataForm: {

				},

				rules: {
					operatorId: [{
						required: true,
						message: '请选择作业人员',
						trigger: 'blur',
					}],
					qty: [{
						required: true,
						validator: qtyValidator,
						trigger: 'blur',
					}],
					ngQty: [{
						required: true,
						validator: ngQtyValidator,
						trigger: '"blur"'
					}],
					actualStartTime: [{
						required: true,
						validator: actualStartTimeValidator,
						trigger: '"blur"'
					}],
					actualEndTime: [{
						required: true,
						validator: actualEndTimeValidator,
						trigger: '"blur"'
					}],
					workHours: [{
						required: true,
						validator: workHoursValidator,
						trigger: '"blur"'
					}],

				},
				employeeNameList: [],
				type: '',
				Name: '',
				fullName: '',
				userId:[]
				
			}
		},
		onReady() {
			this.$refs.reportForm.setRules(this.rules); // 设置校验规则
		},
		watch: {
			
		},

		onLoad(option) {
			const json = JSON.parse(option.params)
			this.type = json.type;
			this.dataForm = json.formData;
			
			this.userId.push(uni.getStorageSync('userId'))
			//console.log(this.userId)
			this.getUserList();
		},
		beforeDestroy() {
			// 移除滚动事件监听
			window.removeEventListener('scroll', this.handleScroll);
		},
		methods: {

			getWorkHours() {
				if (this.reportForm.actualStartTime != "" && this.reportForm.actualEndTime != "") {
					const start = new Date(this.reportForm.actualStartTime);
					const end = new Date(this.reportForm.actualEndTime);
					const diff = Math.abs(end - start)
					this.reportForm.workHours = Math.floor(diff / 1000 / 60)
				}
			},

			// 获取检验员信息
			// employeeChange(e, data) {
			// 	//console.log(data)
			// 	this.Name = data.fullName;
			// 	this.employeeid = data.id
				
			// },
			// 确定
			confirm() {
				this.reportForm.workOrderId = this.dataForm.id
				this.reportForm.status = this.type == '合格' ? 'OK': 'NG'
				this.$refs.reportForm.validate(valid => {
					if (valid) {
						createWorkReport(this.reportForm).then(res => {
							if (res.code == 200) {
								this.$refs.uToast.show({
									title: "提交成功",
									type: 'success',
									duration: 100,
									callback() {
										// 1. 获取当前页面栈实例（此时最后一个元素为当前页）
										let pages = getCurrentPages()
										// 2. 上一页面实例				
										let prevPage = pages[pages.length - 2]
										// 3. 给上一页面实例绑定getValue()方法和参数（注意是$vm）
										prevPage.$vm.getValue("success")
										// 4. 返回上一页面
										uni.navigateBack({
											delta: 1 // 返回的页面数

										})
									}
								});
							}
						})

					} else {
						console.log('false')
					}
				});
			},
			getUserList() {
				
				let query = {
					userId:this.userId
				}
				getUserList(query).then( res =>{
					
					if(res.code == 200){
						
						this.reportForm.operatorId = res.data.list[0].id
						
						 
			
						console.log(this.reportForm.operatorId)
					}
			
					
				})
			}

		}
	}
</script>

<style>
	.form-container {
		padding-bottom: 100rpx;
	}

	.form-item {
		margin: 0 40rpx 0 40rpx;
	}

	.buttom-actions-addsample {
		background-color: #fff;
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 44px;
		box-shadow: 0 -1px 4px #e1e5ec;
		z-index: 20;

		.buttom-btn {
			width: 100%;
			/* #ifndef MP */
			height: 88rpx !important;
			line-height: 88rpx !important;
			border-radius: 0 !important;

			&::after {
				border: none !important;
			}

			/* #endif */
			/* #ifdef MP */
			.u-btn {
				width: 100%;
				height: 88rpx !important;
				line-height: 88rpx !important;
				border-radius: 0 !important;

				&::after {
					border: none !important;
				}
			}

			/* #endif */
		}
	}
</style>